'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async register() {
    const { ctx } = this;
    const { username, password, nickname, avatar, signature } = ctx.request.body;
    if (!username || !password) {
      ctx.body = {
        code: 500,
        msg: '用户名密码不能为空',
        data: null,
      };
    }
    const userInfo = await ctx.service.user.getUserByName(username);
    if (userInfo) {
      ctx.body = {
        code: 500,
        msg: '用户名已被注册',
        data: null,
      };
      return;
    }
    const result = await ctx.service.user.register({
      username,
      password,
      nickname,
      avatar,
      signature,
    });
    if (result) {
      ctx.body = {
        code: 200,
        msg: '注册成功',
        data: null,
      };
    } else {
      ctx.body = {
        code: 500,
        msg: '注册失败',
        data: result,
      };
    }
  }

  async login() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body;
    const userInfo = await ctx.service.user.getUserByName(username);
    console.log(userInfo);
    if (!userInfo) {
      ctx.body = {
        code: 500,
        msg: '用户不存在',
        data: null,
      };
      return;
    }
    if (password !== userInfo.password) {
      ctx.body = {
        code: 500,
        msg: '密码错误',
        data: null,
      };
      return;
    }
    const token = app.jwt.sign({
      id: userInfo.id,
      username: userInfo.username,
      exp: Math.floor(Date.now() / 1000) + (2 * 60 * 60), // token 有效期为 2 小时
    }, app.config.jwt.secret);
    ctx.body = {
      code: 200,
      msg: '登录成功',
      data: {
        token,
      },
    };
  }

  async getUserInfo() {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = app.jwt.verify(token, app.config.jwt.secret);
    const userInfo = await ctx.service.user.getUserByName(decode.username);
    ctx.body = {
      code: 200,
      msg: '请求成功',
      data: {
        id: userInfo.id,
        username: userInfo.username,
        nickname: userInfo.nickname,
        signature: userInfo.signature,
        avatar: userInfo.avatar,
      },
    };
  }

  async updateUserInfo() {
    const { ctx, app } = this;
    const currentUserInfo = ctx.request.body;
    const token = ctx.request.header.authorization;
    const decode = app.jwt.verify(token, app.config.jwt.secret);
    const userInfo = await ctx.service.user.getUserByName(decode.username);
    await ctx.service.user.updateUserInfo({
      ...userInfo,
      ...currentUserInfo,
    });
    ctx.body = {
      code: 200,
      msg: '请求成功',
      data: {},
    };
  }
}

module.exports = UserController;
